//index.js
//获取应用实例
const app = getApp()

var foundedDevices = [];

Page({
  data: {
    motto: 'Hello World',
    userInfo: {},
    hasUserInfo: false,
    canIUse: wx.canIUse('button.open-type.getUserInfo'),
    deviceArray: [
      // { name: "123", RSSI: "65db", deviceId: "1"},
      // { name: "1234", RSSI: "25db",  deviceId: "2" }
    ],
    searchButtonText:'搜索'
  },
  //事件处理函数
  connectButtonTap: function(e) {
    //查看日志
    // wx.navigateTo({
    //   url: '../logs/logs'
    // })

    //关闭扫描
    wx.stopBluetoothDevicesDiscovery({
      success: res => {
        console.log(res);
      }
    });

    var deviceId = e.currentTarget.dataset.id;

    wx.showLoading({
      title: '正在连接中...',
    })

    //连接到设备
    wx.createBLEConnection({
      deviceId: deviceId,
      success: errMsg => {
        wx.hideLoading();
        //跳转至设备页面
        wx.navigateTo({
          url: '../device/device?deviceId=' + deviceId,
        })
      },
      fail: errMsg => {
        console.log("连接到设备失败:", errMsg);
        wx.hideLoading();
        wx.showModal({
          title: "提示",
          content: "连接失败",
          showCancel: false
        })
      }
    })
    console.log("正在连接到设备...");
  },
  onLoad: function () {
    this.openBt();
  },
  getUserInfo: function(e) {
    console.log(e)
    app.globalData.userInfo = e.detail.userInfo
    this.setData({
      userInfo: e.detail.userInfo,
      hasUserInfo: true
    })
  },
  findDevice: function(){

    //检查蓝牙是否可用
    wx.getBluetoothAdapterState({
      success: function (discovering, available, errMsg){
        if(discovering){
          return; 
        }

        if (!available){
          this.openBt();
          return;
        }

        this.discoveryDevice();
      },
      fail: function(){
        wx.showToast({
          title: '获取蓝牙状态失败....'
        })
      }
    })
  },
  discoveryDevice: function(){

    var that = this;

    wx.showToast({
      title: '开始搜索....'
    })

    //当发现设备时
    wx.onBluetoothDeviceFound(function (res) {
      console.log("发现了设备:", res)

      for (var d of res.devices){
        foundedDevices.push(d);
      }

      that.setData({
        deviceArray: foundedDevices
      });

    })

    wx.startBluetoothDevicesDiscovery({
      allowDuplicatesKey: false,
      sucess: function (msg) {
        console.log(msg);

        wx.showToast({
          title: '搜索成功：'
        })

        //获取发现的设备
        wx.getBluetoothDevices({
          success: (devices, msg) => {
            that.setData({
              deviceArray: devices
            })
            console.log("获取设备:", devices)
          }
        })
      }
    })
  },
  openBt: function(){

    wx.onBluetoothAdapterStateChange((available, discovering) => {
      if (available && discovering) {
        this.setData({
          searchButtonText: "搜索中"
        });
      } else if (!available) {
        this.setData({
          searchButtonText: "蓝牙不可用"
        });
      } else {
        this.setData({
          searchButtonText: "搜索"
        });
      }
    });

    //打开蓝牙
    wx.openBluetoothAdapter({
      success: res => {
        //开始扫描设备
        this.discoveryDevice();
      },
      fail: function (res) {
        //提示打开蓝牙
        wx.showModal({
          title:"提示", 
          content:"请打开蓝牙",
          showCancel: false
        })
      }
    });
  }
})
